<?php

namespace app\index\controller;

use app\index\model\Article as ModelArticle;
use frame\lib\Db;
use frame\lib\VerfiyParam;

class Article extends Base
{
    public function index()
    {
        $this->view();
    }
    public function list()
    {
        // 标题搜索
        $query = @$_GET['article'];
        $where = [];
        // Where 搜索 status => 1 , delete_time = 0
        $type = @$_GET['type'] ?? 1;
        $list = ModelArticle::list($where, $query);
        success($list);
    }
    public function edit()
    {
        $id = @$_GET['id'];
        if (!empty($id)) {
            $art = Db::name('article')->where(['id' => $id, 'delete_time' => 0, 'user_id' => $this->uid])->find();
            if (!$art) error('文章不存在');
            $this->view('edit', ['data' => $art]);
            die;
        }
        error('参数id不能为空', 201);
    }
    public function doEdit()
    {
        $param = $_POST;
        $art = Db::name('article')->where(['id' => @$param['id'], 'delete_time' => 0, 'user_id' => $this->uid])->find();
        if (!$art) error('文章不存在');
        $data = [
            'title' => !empty($param['title']) ? preventXSS($param['title']) : $art['title'],
            'content' => !empty($param['content']) ? preventXSS($param['content']) : $art['content'],
            'status' => @$param['status'] == 1 ? 1 : 0,
            'update_time' => getTime()
        ];
        $res = Db::name('article')->where(['user_id' => $this->uid, 'id' => $param['id']])->update($data);
        if ($res) success();
        error();
    }
    public function add()
    {
        $this->view('add');
    }
    public function doAdd()
    {
        $param = $_POST;
        $rule = [
            'title|标题' => 'require',
            'content|内容' => 'require',
            'status' => 'in:1,0'
        ];
        VerfiyParam::init($param, $rule);
        $uid = $this->uid;
        $data = [
            'title' => preventXSS($param['title']),
            'content' => preventXSS($param['content']),
            'status' => @$param['status'] ?? 1,
            'uid' => 0,
            'user_id' => $uid,
            'create_time' => date('Y-m-d H:i:s', time())
        ];
        request_limit('article', "user_id = $uid", 30);
        $res = Db::name('article')->insert($data);
        if ($res) success();
        error();
    }
    public function del()
    {
        $id = @$_GET['id'];
        if (!$id) error('缺少参数ID', 201);
        $id = explode(',', $_GET['id']);
        $res = Db::name('article')->where(['user_id'  => $this->uid, 'delete_time' => 0])->whereIn('id', $id)->delete();
        if ($res) success();
        error();
    }
}
